package com.groupbuying.cheetah.utils;

import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @Author gxy
 * @Description 导出excel工具类
 * @Date 2019/7/23 16:22
<<<<<<< HEAD
 **/
public class ExcelUtils {
    private static Logger log = LoggerFactory.getLogger(ExcelUtils.class);

    public static final Color color = new Color(244, 177, 131);

    public ExcelUtils() {
    }
    public static void writeExcelByObject(List<Map<String, String>> dataset, HttpServletResponse response, String tableName, Object[] headers, Object[] columns)
    {
        try
        {
            XSSFWorkbook workbook = new XSSFWorkbook();

            XSSFSheet sheet = workbook.createSheet(tableName);

            sheet.setDefaultColumnWidth(15);

            XSSFCellStyle style = workbook.createCellStyle();




            XSSFColor myColor = new XSSFColor(color);
            style.setFillForegroundColor(myColor);

            style.setFillPattern((short)1);

            style.setBorderBottom((short)1);
            style.setBorderLeft((short)1);
            style.setBorderRight((short)1);
            style.setBorderTop((short)1);
            style.setAlignment((short)2);

            XSSFFont font = workbook.createFont();
            font.setFontHeightInPoints((short)12);
            font.setBoldweight((short)700);

            style.setFont(font);



            XSSFCellStyle style2 = workbook.createCellStyle();
            style2.setBorderBottom((short)1);
            style2.setBorderLeft((short)1);
            style2.setBorderRight((short)1);
            style2.setBorderTop((short)1);
            style2.setAlignment((short)2);
            style2.setVerticalAlignment((short)1);

            XSSFFont font2 = workbook.createFont();
            font2.setBoldweight((short)400);

            style2.setFont(font2);

            XSSFRow row = sheet.createRow(0);
            String[] heads = (String[])headers;
            if ((headers != null) && (headers.length != 0)) {
                for (int i = 0; i < heads.length; i++) {
                    XSSFCell cell = row.createCell(i);
                    cell.setCellType(1);
                    cell.setCellStyle(style);
                    XSSFRichTextString text = new XSSFRichTextString(heads[i]);
                    cell.setCellValue(text);
                }
            }





            int index = 0;
            Iterator<Map<String, String>> it = dataset.iterator();
            while (it.hasNext()) {
                index++;
                row = sheet.createRow(index);
                Map obj = it.next();

                String trueValue = "";

                String falseValue = "";

                String columnType = "";
                for (int j = 0; j < columns.length; j++)
                {
                    XSSFCell cell = row.createCell(j);
                    cell.setCellType(1);
                    cell.setCellStyle(style2);
                    Object objFieldName = columns[j];
                    if ((objFieldName instanceof String[])) {
                        String[] objArray = (String[])objFieldName;
                        if (objArray.length > 1) {
                            objFieldName = objArray[0];
                            columnType = objArray[1];

                            if (objArray.length > 2) {
                                trueValue = objArray[2];
                            }
                            if (objArray.length > 3) {
                                falseValue = objArray[3];
                            }
                        } else {
                            objFieldName = objArray[0];
                        }
                    }
                    String fieldName = (String)objFieldName;

                    Object value = obj.get(fieldName);
                    String objValue = null;
                    if (value == null) {
                        objValue = "";
                    } else if ((value instanceof Date)) {
                        Date date = (Date)value;
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        objValue = sdf.format(date);
                    } else if ((value instanceof Double)) {
                        Double p = (Double)value;
                        DecimalFormat sf = new DecimalFormat("#.##");
                        objValue = sf.format(p);
                    } else {
                        objValue = String.valueOf(value);
                    }
                    if (objValue != null) {
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                        Matcher matcher = p.matcher(objValue);
                        if (matcher.matches())
                        {
                            cell.setCellValue(Double.parseDouble(objValue));
                        } else {
                            XSSFRichTextString xssfValue = new XSSFRichTextString(objValue);
                            if ("boolean".equalsIgnoreCase(columnType)) {
                                if ("true".equals(String.valueOf(xssfValue))) {
                                    cell.setCellValue(trueValue);
                                } else if ("false".equals(String.valueOf(xssfValue))) {
                                    cell.setCellValue(falseValue);
                                } else {
                                    cell.setCellValue(xssfValue);
                                }
                            } else {
                                cell.setCellValue(xssfValue);
                            }
                        }
                    }
                }
            }

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                workbook.write(os);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);

            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(new StringBuilder().append(tableName).append(System.currentTimeMillis()).append(".xlsx").toString().getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();

            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;

            try
            {
                bis = new BufferedInputStream(is);
                bos = new BufferedOutputStream(out);

                byte[] buff = new byte['?'];

                int bytesRead;

                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
            }
            catch (IOException e) {
                throw e;
            } finally {
                if (bis != null)
                    bis.close();
                if (bos != null)
                    bos.close();
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
